<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    canvas {
      display: block;
      border: 1px solid #000;
      margin: 20px auto;
    }
  </style>
</head>

<body>
  <canvas id="myCanvas"></canvas>
  <script>
    let canvas = document.getElementById('myCanvas');
    let ctx = canvas.getContext('2d');
    canvas.width = document.documentElement.clientWidth - 50;
    canvas.height = document.documentElement.clientHeight - 50;
    let ballArr = []
    class Ball {
      constructor() {
        this.x = parseInt(Math.random() * canvas.width);
        this.y = parseInt(Math.random() * canvas.height);
        this.r = 10;
        this.color = this.getRandom()
        this.dx = parseInt(Math.random() * 10) - 5
        this.dy = parseInt(Math.random() * 10) - 5
        this.index=ballArr.length-1;
        ballArr.push(this)
      }
      update() {
        this.x += this.dx;
        this.y += this.dy;
        if (this.x < this.r || this.x > canvas.width - this.r) {
          this.dx = -this.dx;
        }
        if (this.y < this.r || this.y > canvas.height - this.r) {
          this.dy = -this.dy
        }
      }
      render() {
        ctx.beginPath();
        ctx.globalAlpha = 1;
        ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2);
        ctx.fillStyle = this.color;
        ctx.fill();
        for (let i = this.index; i < ballArr.length; i++) {
          if (Math.abs(ballArr[i].x - this.x) < 150 && Math.abs(ballArr[i].y - this.y) < 150) {
            ctx.strokeStyle = "#000";
            ctx.beginPath();
            ctx.globalAlpha = 10 / Math.sqrt(Math.pow(ballArr[i].x - this.x, 2) + Math.pow(ballArr[i].y - this.y, 2))
            ctx.moveTo(this.x, this.y);
            ctx.lineTo(ballArr[i].x, ballArr[i].y)
            ctx.closePath()
            ctx.stroke()
          }
        }

      }
      getRandom() {
        var allType = "0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f";
        var allTypeArr = allType.split(',');
        var color = "#";
        for (let i = 0; i < 6; i++) {
          let random = parseInt(Math.random() * allTypeArr.length)
          color += allTypeArr[random];
        }
        return color;
      }

    }
    for (let i = 0; i < 20; i++) {
      new Ball()
    }
    setInterval(() => {
      ctx.clearRect(0, 0, canvas.width, canvas.height)
      for (let i = 0; i < ballArr.length; i++) {
        ballArr[i].update()
        ballArr[i].render();

      }
    }, 20);
  </script>
</body>

</html>